package utils

import (
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/load"
	"github.com/shirou/gopsutil/mem"
)

// 定义常量
const (
	B  = 1
	KB = 1024 * B
	MB = 1024 * KB
	GB = 1024 * MB
)

type HostInfo struct {
	Disk string `json:"disk"`
	Cpu  string `json:"cpu"`
	Ram  string `json:"ram"`
}

// HostCheck 检查服务器状态信息
func HostCheck() HostInfo {
	disk := diskCheck()
	cpu := cpuCheck()
	ram := ramCheck()
	hostInfo := HostInfo{
		Disk: disk,
		Cpu:  cpu,
		Ram:  ram,
	}
	return hostInfo
}

// diskCheck 磁盘信息
func diskCheck() string {
	u, _ := disk.Usage("/")

	usedMB := int(u.Used) / MB
	usedGB := int(u.Used) / GB
	totalMB := int(u.Total) / MB
	totalGB := int(u.Total) / GB
	usedPercent := int(u.UsedPercent)

	text := "OK"

	if usedPercent >= 95 {
		text = "CRITICAL"
	} else if usedPercent >= 90 {
		text = "WARNING"
	}

	message := fmt.Sprintf("%s - Disk Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
	return message
}

// cpuCheck CPU信息
func cpuCheck() string {
	cores, _ := cpu.Counts(false)

	a, _ := load.Avg()
	l1 := a.Load1
	l5 := a.Load5
	l15 := a.Load15

	text := "OK"

	if l5 >= float64(cores-1) {
		text = "CRITICAL"
	} else if l5 >= float64(cores-2) {
		text = "WARNING"
	}

	message := fmt.Sprintf("%s - CPU Load average: %.2f, %.2f, %.2f | Cores: %d", text, l1, l5, l15, cores)
	return message
}

// ramCheck 内存信息
func ramCheck() string {
	u, _ := mem.VirtualMemory()

	usedMB := int(u.Used) / MB
	usedGB := int(u.Used) / GB
	totalMB := int(u.Total) / MB
	totalGB := int(u.Total) / GB
	usedPercent := int(u.UsedPercent)

	text := "OK"

	if usedPercent >= 95 {
		text = "CRITICAL"
	} else if usedPercent >= 90 {
		text = "WARNING"
	}

	message := fmt.Sprintf("%s - RAM Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
	return message
}
